package org.sundatagroup.aurora.core.service.message;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.gson.JsonElement;

/**
 * <p>消息订阅发布中的消息中心, 接收消息的发布, 并逐个转发给所有订阅的类、服务等
 * </p>
 * 
 * @author Zdream
 * @date 2018-05-23
 * @since 0.2.0
 */
@Component
public class MessageCenter {
	
    private final static Logger LOGGER = LoggerFactory.getLogger(MessageCenter.class);

	@Autowired
    MessageExecuter executer;
	
	HashMap<String, HashSet<IMessageReciever>> recvers = new HashMap<>();

	/**
	 * 注册
	 * @param reciever
	 *   消息接收方
	 * @param msgs
	 *   消息类型
	 */
	public void register(IMessageReciever reciever, String... msgs) {
		if (reciever == null) {
			throw new NullPointerException("消息接收者 reciever = null");
		}
		
		for (int i = 0; i < msgs.length; i++) {
			String msg = msgs[i];
			
			HashSet<IMessageReciever> set = null;
			if (!recvers.containsKey(msg)) {
				set = new HashSet<>();
				recvers.put(msg, set);
			} else {
				set = recvers.get(msg);
			}
			set.add(reciever);
		}
	}
	
	/**
	 * 发布消息
	 * @param msgs
	 *   消息类型
	 * @param data
	 *   消息数据
	 */
	public void publish(String msg, JsonElement data) {
		if (msg == null) {
			throw new NullPointerException("消息类型 msg = null");
		}
		
		HashSet<IMessageReciever> set = recvers.get(msg);
		if (set == null || set.isEmpty()) {
			return;
		}
		
		for (Iterator<IMessageReciever> it = set.iterator(); it.hasNext();) {
			IMessageReciever reciever = it.next();
			LOGGER.debug("发布异步消息: " + msg);
			executer.doRecieve(reciever, msg, data);
		}
	}
	
}
